import { useState, useRef } from 'react';
import styles from './index.less';
import { Radio, Tooltip, Select, InputNumber } from 'antd';
import { connect } from 'umi';

import { TRMessage } from '#/components';
import { question, sell, buy, maxPrice, minPrice, tradeUnit, upHide, downShow } from '@/assets';

import { UnitDetailModal, SelectStations, TradeTable } from '../';
import { success, fail } from '@/assets/rollingBatch';
import { TRADE_STRATEGY, PROGARM_STATUS, SUBMIT_TYPE, UNIT_STATUS } from '../../constant/enums';
import messageContant from '../../constant/message';
import { arrHasElement } from '../../utils';
import { getChangeTradeStrategyPayload } from '../../utils';
import { DownSquareOutlined, UpSquareOutlined } from '@ant-design/icons';

const { Option } = Select;

function ProgramSetting({
  permissions,
  currentProgramInfo,
  unitList,
  hourOrderList,
  selectedRowKeys,
  priceLimitInfo,
  currentSequenceId,
  dispatch,
}) {
  const unitDetailModalRef = useRef(),
    [power, setPower] = useState({
      submitType: SUBMIT_TYPE.INSTALLED_CAPACITY,
      value: 0,
    }),
    [showTradeUnitList, setShowTradeUnitList] = useState(false);

  /**
   * 校验当前多选是否选中行
   * @param {Function} func 要执行的方法
   * @returns
   */
  const validSelectedRow = (func) => {
    if (!arrHasElement(selectedRowKeys)) {
      TRMessage.warning(messageContant.SELECT_NONE_TABLE_ROW_WARNING_MESSAGE);
      return;
    }
    func();
  };

  /**
   * 批量设置策略
   * @param {*} tradeStrategyType
   * @returns
   */
  const setTradeStrategyType = (tradeStrategyType) =>
    validSelectedRow(() => {
      let modifyHourOrderList = hourOrderList.filter(
          ({ hourOrder }) => selectedRowKeys.indexOf(hourOrder) !== -1,
        ),
        limitInfo = priceLimitInfo[currentSequenceId],
        modifyInfo = getChangeTradeStrategyPayload(
          modifyHourOrderList,
          tradeStrategyType,
          limitInfo,
        );
      dispatch({ type: 'rollingBatch/modifyProgramInfoContent', payload: { modifyInfo } });
    });

  /**
   * 批量设置限额价格
   * @param {Number} type  0→最高价、1→最低价
   * @returns
   */
  const setPriceLimit = (type) =>
    validSelectedRow(() => {
      let modifyInfo = {},
        hourOrdersPriceLimit = priceLimitInfo[currentSequenceId];
      selectedRowKeys.forEach(
        (hourOrder) =>
          (modifyInfo[hourOrder] = {
            price:
              type === 0
                ? hourOrdersPriceLimit[hourOrder].priceUpperLimit
                : hourOrdersPriceLimit[hourOrder].priceLowerLimit,
          }),
      );
      dispatch({ type: 'rollingBatch/modifyProgramInfoContent', payload: { modifyInfo } });
    });

  /**
   * 批量设置
   */
  const setCheckedPower = () => {
    let modifyInfo = {};
    if (!arrHasElement(selectedRowKeys)) {
      TRMessage.warning(messageContant.SELECTED_NONE_HOUR_ORDER_ROW_WARNING_MESSAGE);
      return;
    }
    selectedRowKeys.forEach(
      (hourOrder) => (modifyInfo[hourOrder] = { submitType: power.submitType, power: power.value }),
    );
    dispatch({ type: 'rollingBatch/modifyProgramInfoContent', payload: { modifyInfo } });
  };

  /**
   * 是否显示遮罩层
   * @returns
   */
  const validShowCover = () => {
    if (!permissions.modify) {
      return true;
    }
    switch (currentProgramInfo?.status) {
      case PROGARM_STATUS.CREATE:
      case PROGARM_STATUS.SAVE:
      case PROGARM_STATUS.FAIL:
        return false;
      default:
        return true;
    }
  };
  /**
   * 当前表单模式是否是固定值
   * @returns
   */
  const chooseFixedFlag = () => power.submitType === SUBMIT_TYPE.FIXED;

  /**
   * 当前表单模式是否是比例模式
   * @returns
   */
  const chooseRatioFlag = () =>
    power.submitType === SUBMIT_TYPE.INSTALLED_CAPACITY ||
    power.submitType === SUBMIT_TYPE.TRADE_LIMIT;

  /**
   * 方案的场站列表渲染
   * @returns
   */
  const programUnitListRender = () =>
    unitList.map(({ unitId, unitTitle, unitStatus }, index) => (
      <span key={unitId}>
        {unitStatus === UNIT_STATUS.SUBMIT_SUCCESS ? (
          <img src={success} />
        ) : unitStatus === UNIT_STATUS.SUBMIT_FAIL ? (
          <img src={fail} />
        ) : (
          ''
        )}
        {unitTitle}
        {index != unitList.length - 1 ? '、' : ''}
      </span>
    ));

  const adjustTooltipContentRender = () => (
    <span>
      勾选本项:
      <br />
      1、平台不会对申报超额情况报错提醒，并会自动将超额申报值调整为最大限额值；
      <br />
      2、平台不会对申报交易方向冲突情况报错提醒，并会自动将冲突时段调整为&quot;无策略&quot;
      <br />
      不勾选本项:
      <br />
      1、申报超限额时会报错提醒
      <br />
      2、申报交易方向冲突时会报错并无法保存。
    </span>
  );

  return (
    <div className={styles.programSetting}>
      <div className={styles.stationsAndOperate}>
        <div className={styles.stations}>
          <SelectStations />
        </div>
        <div className={styles.operate}>
          <div className={styles.acceptLimitAdjust}>
            <Radio
              checked={currentProgramInfo?.adjustFlag}
              onClick={() => dispatch({ type: 'rollingBatch/modifyProgramInfoAdjust' })}
            >
              接受限额方向调剂
            </Radio>
            <Tooltip placement="bottom" title={adjustTooltipContentRender()}>
              <img className={styles.icon} src={question} />
            </Tooltip>
          </div>
          <div className={`${styles.setTradeDirection} border-radius-5`}>
            <div
              className={styles.setToSell}
              onClick={() => setTradeStrategyType(TRADE_STRATEGY.SELL)}
            >
              <img src={sell} />
              <span className={styles.text}>一键卖出</span>
            </div>
            <div
              className={styles.setToBuy}
              onClick={() => setTradeStrategyType(TRADE_STRATEGY.BUY)}
            >
              <img src={buy} />
              <span className={styles.text}>一键买入</span>
            </div>
          </div>
          <div className={`${styles.setTradePrice} border-radius-5`}>
            <div className={styles.setToMax} onClick={() => setPriceLimit(0)}>
              <img src={maxPrice} />
              <span className={styles.text}>一键最高价</span>
            </div>
            <div className={styles.setToMin} onClick={() => setPriceLimit(1)}>
              <img src={minPrice} />
              <span className={styles.text}>一键最低价</span>
            </div>
          </div>
          <div className={`${styles.setPower} border-radius-5`}>
            <Radio
              checked={chooseRatioFlag()}
              onClick={() => setPower({ submitType: SUBMIT_TYPE.INSTALLED_CAPACITY, value: 0 })}
            />
            <Select
              value={chooseFixedFlag() ? SUBMIT_TYPE.INSTALLED_CAPACITY : power.submitType}
              bordered={false}
              onChange={(submitType) => setPower({ submitType, value: 0 })}
              disabled={chooseFixedFlag()}
            >
              <Option className={styles.powerTypeOption} value={SUBMIT_TYPE.INSTALLED_CAPACITY}>
                装机容量
              </Option>
              <Option className={styles.powerTypeOption} value={SUBMIT_TYPE.TRADE_LIMIT}>
                交易限额
              </Option>
            </Select>
            <span className={styles.label}>比例</span>
            <InputNumber
              min={0}
              max={100}
              precision={0}
              className={styles.value}
              value={chooseRatioFlag() ? power.value * 100 : 0}
              onChange={(value) => setPower({ ...power, value: value / 100 })}
              disabled={chooseFixedFlag()}
            />

            <div className={styles.splitLine} />

            <Radio
              checked={chooseFixedFlag()}
              onClick={() => setPower({ submitType: SUBMIT_TYPE.FIXED, valyue: 0 })}
            />
            <span className={styles.label}>固定值</span>
            <InputNumber
              min={0}
              precision={3}
              className={styles.value}
              value={chooseFixedFlag() ? power.value : 0}
              onChange={(value) => setPower({ ...power, value })}
              disabled={chooseRatioFlag()}
            />

            <div className={styles.btn} onClick={setCheckedPower}>
              批量设置
            </div>
          </div>
        </div>
      </div>
      <div className={`${styles.tradeUnitList} border-radius-5`}>
        <img className={styles.tradUnitIcon} src={tradeUnit} />
        <div className={`${styles.tradUnitText} ${showTradeUnitList ? styles.show : ''}`}>
          <span className={styles.label}>交易单元: </span>
          <span className={styles.value}>{programUnitListRender()}</span>
        </div>
        {/* <img
          className={styles.showIcon}
          src={showTradeUnitList ? upHide : downShow}
          onClick={() => {
            setShowTradeUnitList(!showTradeUnitList);
          }}
        /> */}
        {showTradeUnitList ? (
          <UpSquareOutlined
            onClick={() => setShowTradeUnitList(!showTradeUnitList)}
            className={styles.showIcon}
          />
        ) : (
          <DownSquareOutlined
            onClick={() => setShowTradeUnitList(!showTradeUnitList)}
            className={styles.showIcon}
          />
        )}
      </div>
      <TradeTable />
      <UnitDetailModal ref={unitDetailModalRef} />
      {/* 遮罩层 */}
      {validShowCover() ? <div className={styles.cover} /> : ''}
    </div>
  );
}

export default connect(
  ({
    rollingBatch: {
      currentProgramPermission: permissions,
      currentProgramInfo,
      selectedRowKeys,
      currentProgramHourOrderList: hourOrderList,
      currentUnitList: unitList,
      globalSequence: {
        current: { tradeSequenceId: currentSequenceId },
      },
      priceLimitInfo,
    },
  }) => ({
    permissions,
    currentProgramInfo,
    unitList,
    selectedRowKeys,
    priceLimitInfo,
    currentSequenceId,
    hourOrderList,
  }),
)(ProgramSetting);
